package jwt

import (
	"go_backend/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

// JWT is jwt middleware
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		token := c.Request.Header.Get("token")
		if token == "" {
			code = -1
		} else {
			_, err := utils.ParseToken(token)
			if err != nil {
				code = -1
			}
		}

		if code != 0 {
			c.JSON(http.StatusUnauthorized, gin.H{
				"status": code,
				"msg":    "登录凭证验证失败",
				"result": data,
			})

			c.Abort()
			return
		}

		c.Next()
	}
}
